package com.kylin.bq;

import com.kylin.lock8.Test1;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

//阻塞队列
public class Test {
    public static void main(String[] args) throws InterruptedException {
        //test1();
        //test2();
        //test3();
        test4();


    }

    //抛出异常
    public static void test1() {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.add("a"));//true
        System.out.println(blockingQueue.add("b"));//true
        System.out.println(blockingQueue.add("c"));//true

        //java.lang.IllegalStateException: Queue full 抛出队列满异常
        //System.out.println(blockingQueue.add("d"));

        System.out.println(blockingQueue.element());//查看队列首元素 a 没有抛出异常java.util.NoSuchElementException

        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        System.out.println(blockingQueue.remove());
        //java.util.NoSuchElementException 队列中没有元素
        System.out.println(blockingQueue.remove());

    }

    //不抛出异常 返回值
    public static void test2() {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(3);

        System.out.println(blockingQueue.offer("a"));//true
        System.out.println(blockingQueue.offer("b"));//true
        System.out.println(blockingQueue.offer("c"));//true

        //队列满的时候添加返回false,不抛出异常
        //System.out.println(blockingQueue.offer("d"));

        System.out.println(blockingQueue.peek());//查看队列首元素 a 没有为null

        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        //队列空的时候，移除元素返回null
        System.out.println(blockingQueue.poll());
    }


    //等待，阻塞（一直阻塞）
    public static void test3() throws InterruptedException {
        //队列的大小
        ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);

        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
        //队列已满 一直阻塞直到能添加进队列中
        //blockingQueue.put("d");

        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        System.out.println(blockingQueue.take());
        //当前队列为空，也为一直阻塞状态
        System.out.println(blockingQueue.take());

    }

    //等待，阻塞（等待超时）
    public static void test4() throws InterruptedException {
        ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3);

        blockingQueue.offer("a");
        blockingQueue.offer("b");
        blockingQueue.offer("c");
        //当队列满的时候无法添加，阻塞等待两秒中后结束
        //blockingQueue.offer("d",2, TimeUnit.SECONDS);

        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        //队列为空无法取出元素，阻塞等待两秒中后结束返回null
        System.out.println(blockingQueue.poll(2, TimeUnit.SECONDS));
    }
}
